<template>
  <div>
    <common-head :title="$route.name"/>
    <div id="loginbox">
      <div class="wylogo">
        <img src="../../assets/img/Login.png" alt="" />
      </div>
      <van-form @submit="onSubmit">
        <van-field
          v-model="user.username"
          name="username"
          placeholder="用户名"
          :rules="[{ required: true }]"
        />
        <van-field
          v-model="user.pwd"
          type="password"
          name="pwd"
          placeholder="密码"
          :rules="[{ required: true }]"
        />
        <div style="margin: 16px; display: flex;">
          <van-button round block color="#DD1A21" type="info" native-type="submit">登录</van-button>
          <van-button round block type="info" to="/register">注册</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import CommonHead from '../../components/CommonHead.vue'
import { userLogin } from '_api'
import { Toast } from 'vant'
export default {
  data () {
    return {
      user: {
        username: '',
        pwd: ''
      }
    }
  },
  methods: {
    onSubmit (params) {
      userLogin({
        deviceId: 234567,
        deviceName: 'dwfertyu',
        ...params
      }).then(res => {
        if (res.data.code === 0) {
          localStorage.setItem('uid', res.data.data.uid)
          localStorage.setItem('token', res.data.data.token)
          Toast.success({
            message: '登录成功',
            duration: 1000,
            onClose: () => {
              if (this.$route.query.from) {
                this.$router.replace(this.$route.query.from)
              } else {
                this.$router.replace({
                  name: '首页',
                  params: {
                    id: 1
                  }
                })
              }
            }
          })
        } else {
          Toast.fail('登录失败')
        }
      })
    }
  },
  components: { CommonHead }
}
</script>

<style lang="scss" scoped>
#loginbox {
  padding-top: 46px;
  .wylogo {
    width: 100%;
    height: 45px;
    margin-top: 35px;
    display: flex;
    justify-content: center;
    margin-bottom: 40px;
    img {
      width: 134px;
      height: 45px;
    }
  }
}
</style>
